//package com.guangaiboen.attendance.core.dispatcher.other.simplehttp;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.serializer.SerializerFeature;
//import com.google.common.base.Stopwatch;
//import org.apache.http.HttpEntity;
//import org.apache.http.HttpHeaders;
//import org.apache.http.client.config.RequestConfig;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.client.methods.HttpUriRequest;
//import org.apache.http.client.utils.URIBuilder;
//import org.apache.http.client.utils.URLEncodedUtils;
//import org.apache.http.entity.ContentType;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.message.BasicNameValuePair;
//import org.apache.http.util.EntityUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.io.IOException;
//import java.net.URI;
//import java.nio.charset.Charset;
//import java.nio.charset.StandardCharsets;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.TimeUnit;
//
///**
// * 将常用http请求方式简单封装
// * httpClient作为属性注入，如果默认HttpClientFactoryBean的配置方式无法满足需求，可手动注入
// */
//@Service
//public class SimpleHttpExecutor {
//
//    private static final Logger logger = LoggerFactory.getLogger(SimpleHttpExecutor.class);
//
//    @Autowired
//    private CloseableHttpClient httpClient;
//
//    private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
//
//    public String executePost(String url, ContentType contentType, String body, int timeout) {
//        return execute(url, () -> {
//            HttpPost httpPost = new HttpPost(url);
//            //-1 采用默认超时时间
//            if (timeout > 0) {
//                httpPost.setConfig(createRequestConfig(timeout));
//            }
//            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());
//            //添加 rid
//           // httpPost.setHeader(ClmConstants.TRACE_ID_KEY, MDC.get(ClmConstants.TRACE_ID_KEY));
//            StringEntity entity = new StringEntity(body, contentType);
//            httpPost.setEntity(entity);
//
//            return doExecute(httpPost, contentType.getCharset());
//        });
//    }
//
//    public String executePost(String url, ContentType contentType, String body) {
//        return executePost(url, contentType, body, -1);
//    }
//
//    private String doExecute(HttpUriRequest request, Charset charset) throws IOException {
//        CloseableHttpResponse response = httpClient.execute(request);
//        HttpEntity responseEntity = response.getEntity();
//        int statusCode = response.getStatusLine().getStatusCode();
//        if (statusCode != 200) {
//            EntityUtils.consume(responseEntity);
//            throw new RuntimeException("execute request failed! http status:" + statusCode);
//        }
//        return EntityUtils.toString(responseEntity, charset);
//    }
//
//    public String executeGet(String url, Map<String, String> params, Charset charset, int timeout) {
//        return execute(url, () -> {
//            URIBuilder uriBuilder = new URIBuilder(url);
//            if (params != null) {
//                params.forEach(uriBuilder::addParameter);
//            }
//            if (charset == null) {
//                uriBuilder.setCharset(DEFAULT_CHARSET);
//            } else {
//                uriBuilder.setCharset(charset);
//            }
//            URI build = uriBuilder.build();
//            HttpGet httpGet = new HttpGet(build);
//            if (timeout > 0) {
//                httpGet.setConfig(createRequestConfig(timeout));
//            }
//            return doExecute(httpGet, charset);
//        });
//    }
//
//    public String executeGet(String url, Map<String, String> params, Charset charset) {
//        return executeGet(url, params, charset, -1);
//    }
//
//    public String executeGet(String url, Map<String, String> params) {
//        return executeGet(url, params, DEFAULT_CHARSET, -1);
//    }
//
//    private <T> T execute(String url, SupplierWithE<T, Exception> executionSupplier) {
//        try {
//            Stopwatch stopwatch = Stopwatch.createStarted();
//            T t = executionSupplier.get();
//            long elapsed = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
//            logger.info("request url: {}, spend time: {}ms", url, elapsed);
//            return t;
//        } catch (Exception e) {
//            logger.error("execute request failed! url: " + url, e);
//            throw new RuntimeException(e);
//        }
//    }
//
//
//    public String executePostWithForm(String url, Map<String, String> params, Charset charset, int timeout) {
//        List<BasicNameValuePair> nameValuePairList = new ArrayList<>();
//        if (params != null) {
//            params.forEach((k, v) -> nameValuePairList.add(new BasicNameValuePair(k, v)));
//        }
//        String body = URLEncodedUtils.format(nameValuePairList, charset);
//        return executePost(url, ContentType.APPLICATION_FORM_URLENCODED, body, timeout);
//    }
//
//    public String executePostWithForm(String url, Map<String, String> params, Charset charset) {
//        return executePostWithForm(url, params, charset, -1);
//    }
//
//    public String executePostWithForm(String url, Map<String, String> params) {
//        return executePostWithForm(url, params, DEFAULT_CHARSET);
//    }
//
//    public String executePostWithJson(String url, Object params, Charset charset, int timeout) {
//        String body;
//        if(params instanceof String){
//            body = (String) params;
//        } else {
//            body = JSON.toJSONString(params, SerializerFeature.WriteDateUseDateFormat);
//        }
//        return executePost(url, ContentType.APPLICATION_JSON.withCharset(charset), body, timeout);
//    }
//
//    public String executePostWithJson(String url, Object params, Charset charset) {
//        return executePostWithJson(url, params, charset, -1);
//    }
//
//    public String executePostWithJson(String url, Object params) {
//        return executePostWithJson(url, params, DEFAULT_CHARSET);
//    }
//
//    /**
//     * 为单个请求配置
//     *
//     * @param timeout so timeout
//     * @return RequestConfig
//     */
//    private RequestConfig createRequestConfig(int timeout) {
//        return RequestConfig.custom()
//                .setSocketTimeout(timeout)
//                .build();
//    }
//
//    public void setHttpClient(CloseableHttpClient httpClient) {
//        this.httpClient = httpClient;
//    }
//
//    @FunctionalInterface
//    public interface SupplierWithE<T, X extends Exception> {
//        T get() throws X;
//    }
//}
